//
//  MPBluetoothManage.m
//  MPOSDemoProject
//
//  Created by lfy on 2018/6/6.
//  Copyright © 2018年 develop. All rights reserved.
//

#import "MPBluetoothManager.h"
#import "BabyBluetooth.h"
#define channelOnPeropheralView @"peripheralView"
#import "NSString+HexString.h"

@interface MPBluetoothManager(){
    BluetoothType _type;
    BabyBluetooth *bluetoothShare;
    BabyCentralManager *centralManager;
    DiscoverToPeripheralsBlock discoverBlcok;
    ConnectPeripheralBlock  connectedBlock;
    DisConnectPeripheralBlock disConnectedBlock;
    DiscoverServerBlock  discoverServerBlock;
    DiscoverCharacteristicBlock discoverCharacteristicBlock;
    NSMutableArray  *writeCharacteristicArrs;
    CBPeripheral  *connectedPeripheral;
}

@end

static MPBluetoothManager *manager = nil;

@implementation MPBluetoothManager

+ (instancetype)share {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MPBluetoothManager alloc] init];
    });
    return manager;
}

- (void)setupBlueToothManager:(BluetoothType)type{
    if (type == other) {
        assert("不支持此类型蓝牙连接");
    }
    bluetoothShare = [BabyBluetooth shareBabyBluetooth];
    _type = type;
    [self setupBlueToothBlock];
}

- (void)startScan:(DiscoverToPeripheralsBlock)peripherals{
    self->discoverBlcok = peripherals;
    bluetoothShare.scanForPeripherals().begin();
}

- (void)cancelScan {
    [bluetoothShare cancelScan];
}

- (void)startConnect:(CBPeripheral*)currPeripheral handle:(ConnectPeripheralBlock)connected {
    self->connectedBlock = connected;
    NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};
    NSDictionary *connectOptions = @{CBConnectPeripheralOptionNotifyOnConnectionKey:@YES,
                                     CBConnectPeripheralOptionNotifyOnDisconnectionKey:@YES,
                                     CBConnectPeripheralOptionNotifyOnNotificationKey:@YES};
    
    [bluetoothShare setBabyOptionsAtChannel:channelOnPeropheralView scanForPeripheralsWithOptions:scanForPeripheralsWithOptions connectPeripheralWithOptions:connectOptions scanForPeripheralsWithServices:nil discoverWithServices:nil discoverWithCharacteristics:nil];
    bluetoothShare.having(currPeripheral).and.channel(channelOnPeropheralView).then.connectToPeripherals().discoverServices().discoverCharacteristics().readValueForDescriptors().discoverDescriptorsForCharacteristic().readValueForDescriptors().readValueForCharacteristic().begin();
    [bluetoothShare cancelScan];

}

- (void)disConnect:(DisConnectPeripheralBlock)handle {
    disConnectedBlock = handle;
    [bluetoothShare cancelAllPeripheralsConnection];
}


- (void)registerDiscoverService:(DiscoverServerBlock)handle{
    self->discoverServerBlock = handle;
}

- (void)registerDiscoverCharacteristic:(DiscoverCharacteristicBlock)handle{
    self->discoverCharacteristicBlock = handle;
}


- (void)writeToPeripheralWithString:(NSString *)writeStr {
    NSData *data = [NSString convertHexStrToString:writeStr];
    for (CBCharacteristic *characteristic in writeCharacteristicArrs) {
        [connectedPeripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }
}

- (void)getConnectStatus {
    
}

/**
 初始化蓝牙回调参数
 */
- (void)setupBlueToothBlock {
    __weak typeof(self) weakSelf = self;
    
    /// 蓝牙状态回调
    [bluetoothShare setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        if (central.state == CBCentralManagerStatePoweredOn) {
            /// 设备打开，正在开始搜索蓝牙
            NSLog(@"设备打开，正在开始搜索蓝牙");
        }
    }];
    
    [bluetoothShare setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        /// 扫描到设备回调
        strongSelf->discoverBlcok(central,peripheral,advertisementData,RSSI);
    }];
    
    [bluetoothShare setBlockOnConnectedAtChannel:channelOnPeropheralView block:^(CBCentralManager *central, CBPeripheral *peripheral) {
        /// 链接到某个设备回调
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->connectedPeripheral = peripheral;
        if (strongSelf->connectedBlock) {
            strongSelf->connectedBlock(central,peripheral,nil);
        }
        
    }];
    
    [bluetoothShare setBlockOnFailToConnectAtChannel:channelOnPeropheralView block:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        /// 链接失败
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->connectedPeripheral = nil;
        if(strongSelf->connectedBlock) {
            strongSelf->connectedBlock(central,peripheral,nil);
        }
    }];

    [bluetoothShare setBlockOnDisconnectAtChannel:channelOnPeropheralView block:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        /// 链接失败
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->connectedPeripheral = nil;
        if(strongSelf->disConnectedBlock){
            strongSelf->disConnectedBlock(central,peripheral,error);
        }
    }];
    
    [bluetoothShare setBlockOnDiscoverServicesAtChannel:channelOnPeropheralView block:^(CBPeripheral *peripheral, NSError *error) {
        /// 扫描到某个设备服务
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if(strongSelf->discoverServerBlock){
            strongSelf->discoverServerBlock(peripheral,error);
        }
    }];
    
    [bluetoothShare setBlockOnDiscoverCharacteristicsAtChannel:channelOnPeropheralView block:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        if(error != nil) { return ;}
        __strong __typeof(weakSelf) strongSelf = weakSelf;

        for (CBCharacteristic *characteristic in service.characteristics) {
            NSLog(@"%@,%lu,%@",characteristic,(unsigned long)characteristic.properties,characteristic.value);
            if (characteristic.properties & CBCharacteristicPropertyWriteWithoutResponse || characteristic.properties & CBCharacteristicPropertyWrite) {
                [strongSelf->writeCharacteristicArrs addObject:characteristic];
            }
        }
        
        
        if(strongSelf->discoverCharacteristicBlock) {
            strongSelf->discoverCharacteristicBlock(peripheral,service,error);
        }
    }];
    
    [bluetoothShare setBlockOnReadValueForCharacteristicAtChannel:channelOnPeropheralView block:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {

    }];
    
    [bluetoothShare setBlockOnReadValueForDescriptorsAtChannel:channelOnPeropheralView block:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
        /// 读取Characteristics中的值

    }];
    
    
    [bluetoothShare setBlockOnDidWriteValueForCharacteristicAtChannel:channelOnPeropheralView block:^(CBCharacteristic *characteristic, NSError *error) {
        /// 写入数据成功回调

    }];
    
    //设置查找设备的过滤器
    [bluetoothShare setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        if (peripheralName.length >0) {
            return YES;
        }
        return NO;
    }];
    
    NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};
    //连接设备->
    [bluetoothShare setBabyOptionsWithScanForPeripheralsWithOptions:scanForPeripheralsWithOptions connectPeripheralWithOptions:nil scanForPeripheralsWithServices:nil discoverWithServices:nil discoverWithCharacteristics:nil];
    
}

@end
